/* eslint-disable array-callback-return */
/* eslint-disable consistent-return */
/* eslint-disable no-param-reassign */
import React from 'react';
import { connect } from 'dva';
import {
  DownOutlined,
  PlusOutlined,
  UpOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Input,
  Select,
  DatePicker,
  message,
  Row,
  Col,
  Menu,
  Dropdown,
  Modal,
  Divider,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { confirm } = Modal;

@connect(({ rolemanage, loading }) => ({
  pageData: rolemanage.pageData,
  loading: loading.effects['rolemanage/fetchList'],
  formFieldsValue: rolemanage.formFieldsValue,
  expandForm: rolemanage.expandForm,
  valuesArr: rolemanage.valuesArr,
}))
@Form.create()
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      selectedRowKeys: [],
      systemList: [], // 所属系统
    };
    this.formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'rolemanage/fetchDictCode',
      payload: {},
      callback: response => {
        if (response.success) {
          const sortNumber = (a, b) => a.sysCode - b.sysCode;
          this.setState({ systemList: response.data.sort(sortNumber) });
        } else {
          message.warning(`${response.message || '服务端错误！'}`);
        }
      },
    });
    this.getInitialList();
  };

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      dispatch({
        type: 'rolemanage/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = () => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'rolemanage/updateModelData',
          payload: {
            formFieldsValue: values,
          },
        });
        this.searchList(this.processFormData(values));
      }
    });
  };

  // 查询
  searchList = (formFieldsValue, currentPage = 1, pageSize = 10, isClear = true) => {
    const { dispatch } = this.props;
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const page = { currentPage, pageSizes: pageSize, orderBy: '' };
    const values = {
      ...formFieldsValue,
    };

    dispatch({
      type: 'rolemanage/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'rolemanage/fetchList',
      payload: {
        role: values,
        page,
      },
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'roleName') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      if (key === 'createTime') {
        formFieldsValue.startDate =
          (tempFieldsValue.createTime &&
            tempFieldsValue.createTime[0] &&
            tempFieldsValue.createTime[0].format('YYYY-MM-DD')) ||
          null;
        formFieldsValue.endDate =
          (tempFieldsValue.createTime &&
            tempFieldsValue.createTime[1] &&
            tempFieldsValue.createTime[1].format('YYYY-MM-DD')) ||
          null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      delete formFieldsValue.createTime;
    });
    return formFieldsValue;
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 重置查询
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'rolemanage/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
    form.setFieldsValue({
      createTime: null,
    });
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'rolemanage/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 删除数据
  delList = roleId => {
    const { dispatch, formFieldsValue } = this.props;
    this.setState({ selectedRowKeys: [roleId] });
    confirm({
      title: '你确定要删除此角色信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'rolemanage/deleteBaseRole',
          payload: {
            roleId,
          },
        }).then(res => {
          if (res.success) {
            const { pageData } = this.props;
            this.setState({ selectedRowKeys: [] });
            message.success(`${res.message || '删除成功！'}`);
            this.searchList(
              this.processFormData(formFieldsValue),
              pageData.pagination.current,
              pageData.pagination.pageSize
            );
          } else {
            message.warning(`${res.message || res.data || '删除失败！'}`);
          }
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 修改启用停用状态
  updateStatus = (roleId, roleStatus) => {
    const { dispatch, formFieldsValue } = this.props;
    this.setState({ selectedRowKeys: [roleId] });
    confirm({
      title: `你确定要${roleStatus === '1' ? '停用' : '启用'}此角色状态吗？`,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk: () => {
        roleStatus = roleStatus === 1 ? 2 : 1;
        dispatch({
          type: 'rolemanage/updateBaseRole',
          payload: {
            roleId,
            roleStatus,
          },
        }).then(res => {
          if (res.success) {
            const { pageData } = this.props;
            message.success(`${roleStatus === 1 ? '启用成功！' : '停用成功！'}`);
            this.searchList(
              this.processFormData(formFieldsValue),
              pageData.pagination.current,
              pageData.pagination.pageSize
            );
            this.setState({ selectedRowKeys: [] });
          } else {
            message.warning(`${roleStatus === 1 ? '启用失败！' : '停用失败！'}`);
          }
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    const { systemList } = this.state;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="角色名称" {...this.formItemLayout}>
              {getFieldDecorator('roleName', {
                rules: [{ required: false, message: '最大不超过100个字符', max: 100 }],
                initialValue: formFieldsValue.roleName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所属系统" {...this.formItemLayout}>
              {getFieldDecorator('sysId', {
                initialValue: formFieldsValue.sysId,
              })(
                <HOCSelect placeholder="请选择" showSearch optionFilterProp="children" allowClear>
                  {systemList.map(options => (
                    <Option key={options.sysId}>{options.sysName}</Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={this.searchBtnList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    const { systemList } = this.state;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="角色名称" {...this.formItemLayout}>
              {getFieldDecorator('roleName', {
                rules: [{ required: false, message: '最大不超过100个字符', max: 100 }],
                initialValue: formFieldsValue.roleName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所属系统" {...this.formItemLayout}>
              {getFieldDecorator('sysId', {
                initialValue: formFieldsValue.sysId,
              })(
                <HOCSelect placeholder="请选择" showSearch optionFilterProp="children" allowClear>
                  {systemList.map(options => (
                    <Option key={options.sysId}>{options.sysName}</Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="创建日期" {...this.formItemLayout}>
              {getFieldDecorator('createTime', {
                initialValue: formFieldsValue.createTime,
              })(
                <RangePicker
                  placeholder={['创建开始日期', '创建结束日期']}
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden', textAlign: 'center' }}>
              <span style={{ float: 'right', marginBottom: 16 }}>
                <Button type="primary" onClick={this.searchBtnList}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { pageData, loading } = this.props;
    const { selectedRows, selectedRowKeys, systemList } = this.state;
    const columns = [
      {
        title: '角色名称',
        dataIndex: 'roleName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '所属系统',
        dataIndex: 'sysId',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val =>
          systemList.map(item => {
            if (item.sysId === `${val}`) {
              return <span>{item.sysName}</span>;
            }
          }),
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: (a, b) => new Date(b.createTime) - new Date(a.createTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val ? moment(val).format('YYYY-MM-DD HH:mm') : '暂无'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <Authorized authority="mgr:role:updateBaseRole" noMatch={null}>
              <a onClick={() => router.push(`/systemmanage/role/update?roleId=${record.roleId}`)}>
                修改
              </a>
              <Divider type="vertical" />
            </Authorized>
            <Dropdown
              overlay={
                <Menu>
                  <Menu.Item
                    key="view"
                    onClick={() => router.push(`/systemmanage/role/detail?roleId=${record.roleId}`)}
                  >
                    查看
                  </Menu.Item>
                  {checkPermissions('mgr:role:deleteBaseRole') && (
                    <Menu.Item key="delete" onClick={() => this.delList(record.roleId)}>
                      删除
                    </Menu.Item>
                  )}
                </Menu>
              }
            >
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Row style={{ marginBottom: '16px' }}>
            <Authorized authority="mgr:role:insertBaseRole" noMatch={null}>
              <Button
                type="primary"
                onClick={() => router.push('/systemmanage/role/add')}
                icon={<PlusOutlined />}
              >
                新增
              </Button>
            </Authorized>
          </Row>
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            loading={loading}
            data={pageData}
            rowKey="roleId"
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            style={{ background: '#fff' }}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
